package com.hxgz.steel.controller.portal;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxgz.steel.common.Const;
import com.hxgz.steel.common.RedisPool;
import com.hxgz.steel.common.ResponseCode;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.domain.CompanyCert;
import com.hxgz.steel.domain.User;
import com.hxgz.steel.service.BackendUserService;
import com.hxgz.steel.service.UserService;
import com.hxgz.steel.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("iuser")
@Api(tags = "UserContorller", description = "前台-用户登陆-个人中心相关")
@Slf4j
public class UserContorller {

  private static final Logger logger = LoggerFactory.getLogger(UserContorller.class);

  @Autowired
  private UserService userService;
  @Autowired
  private BackendUserService buSerevice;
  @Autowired
  public OSSClientUtil ossutil;


  @RequestMapping(value = "updateUser.do", method = RequestMethod.POST)
  @ApiOperation("个人信息-修改")
  public ServerResponse updateUser(User user, HttpServletRequest request) {
    User newUser = Const.checkUserLogin(request);
    user.setStatus(newUser.getStatus());
    return userService.updateUser(user);
  }

  /**
   * 用户登录
   */
  @RequestMapping(value = "userLogin.do", method = RequestMethod.POST)
  @ApiOperation("用户登录")
  public ServerResponse<Map<String, Object>> userLogin(HttpServletResponse httpServletResponse,
      HttpServletRequest httpServletRequest,
      HttpSession session,
      String username, String password, String code) {
    ServerResponse<Map<String, Object>> response = userService
        .userLogin(username, password, code, httpServletRequest, httpServletResponse);
    if (response.isSuccess()) {
      CookieUtil.writeLoginToken(httpServletResponse, session.getId());
      logger.info("登陆人的sessionId为 ------  " + session.getId());
      RedisPoolUtil.set(session.getId(), JsonUtil.obj2String(response.getData().get("user")));
      logger.info("redis中存的值为   ------ " + RedisPoolUtil.get(session.getId()));
      response.getData().put("request", session.getId());
    }
    return response;
  }

  @RequestMapping(value = "smsLogin.do", method = RequestMethod.POST)
  @ApiOperation("短信登录")
  public ServerResponse<User> smsLogin(HttpServletResponse httpServletResponse, HttpSession session,
      String username, String yards, String code, HttpServletRequest httpServletRequest) {
    String myYards = RedisPoolUtil.get(username);
    if (!StringUtils.contains(yards, myYards)) {
      return ServerResponse.createByErrorMessage("验证码有误！");
    }
    ServerResponse<User> response = userService
        .smsLogin(username, httpServletRequest, httpServletResponse,code);
    if (response.isSuccess()) {
      RedisPoolUtil.del(username);
      CookieUtil.writeLoginToken(httpServletResponse, session.getId());
      RedisPoolUtil.set(session.getId(), JsonUtil.obj2String(response.getData()));
    }
    return response;
  }

  /**
   * 用户登出
   */
  @RequestMapping(value = "logout.do", method = RequestMethod.POST)
  @ApiOperation("用户登出")
  public ServerResponse<String> logout(HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse) {
    String loginToken = CookieUtil.readLoginToken(httpServletRequest);
    CookieUtil.delLoginToken(httpServletRequest, httpServletResponse);
    RedisPoolUtil.del(loginToken);
    return ServerResponse.createBySuccess("登出成功");
  }

  /**
   * 用户注册
   */
  @RequestMapping(value = "register.do", method = RequestMethod.POST)
  @ApiOperation("用户注册")
  public ServerResponse<String> register(@RequestParam String phone,
      @RequestParam String password,
      @ApiParam(value = "验证码", required = true) @RequestParam String yards) {
    String myYards = RedisPoolUtil.get(phone);
    if (!StringUtils.contains(yards, myYards)) {
      return ServerResponse.createByErrorMessage("验证码有误！");
    }
    try {
      ServerResponse serverResponse = userService.register(phone, password);
      return serverResponse;
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("注册失败");
    }
  }

  /**
   * 获取短信
   */
  @RequestMapping(value = "getSMS.do", method = RequestMethod.POST)
  @ApiOperation("获取短信")
  public ServerResponse getSMS(@RequestParam String phone) {
    String identify = SendMsgUtil.sendIdentifyByDX(phone);
    if (StringUtils.isEmpty(identify)) {
      return ServerResponse.createByErrorMessage("操作失败");
    }
    RedisPoolUtil.setEx(phone, identify,
        Const.RedisCacheExtime.REDIS_YARD_EXTIME);
    return ServerResponse.createBySuccess("发送成功");
  }

  /**
   * 个人中心-修改密码
   */
  @RequestMapping(value = "updatePwd.do", method = RequestMethod.POST)
  @ApiOperation("个人中心-修改密码")
  public ServerResponse updatePwd(@RequestParam String phone, @RequestParam String password,
      @ApiParam("验证码") @RequestParam String yards) {
    String myYards = RedisPoolUtil.get(phone);
    if (!StringUtils.contains(yards, myYards)) {
      return ServerResponse.createByErrorMessage("验证码有误！");
    }
    return userService.updatePwd(phone, password);
  }


  /**
   * 公司认证-提交
   */
  @RequestMapping(value = "addCompanyCert.do", method = RequestMethod.POST)
  @ApiOperation("公司认证-提交")
  public ServerResponse addCompanyCert(HttpServletRequest httpServletRequest,
      CompanyCert companyCert) {
    User user = Const.checkUserLogin(httpServletRequest);
    if (user == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }
    companyCert.setUserId(user.getId());
    return userService.companyCert(companyCert);
  }

  /**
   * 公司认证-审核详情
   */
  @RequestMapping(value = "companyCertInfo.do", method = RequestMethod.POST)
  @ApiOperation("公司认证-审核详情")
  public ServerResponse<CompanyCert> companyCertInfo(HttpServletRequest httpServletRequest) {
    User user = Const.checkUserLogin(httpServletRequest);
    if (user == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }
    return userService.companyCertInfo(user.getId());
  }

  @RequestMapping(value = "bindBank.do", method = RequestMethod.POST)
  @ApiOperation("个人信息绑定银行卡")
  public ServerResponse bindBank(@ApiParam("姓名") @RequestParam String realName,
      @ApiParam("银行卡号") @RequestParam String bankNo,
      @ApiParam("身份证号") @RequestParam String idno,
      @ApiParam("手机号") @RequestParam String phone,
      @ApiParam("头像") @RequestParam(required = false) String headpic,
      HttpServletRequest httpServletRequest, HttpSession session) {
    User loginUser = Const.checkUserLogin(httpServletRequest);
    if (loginUser == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }

    String msg = "";
    String host = PropertiesUtil.getProperty("bank.binding.host");
    String path = PropertiesUtil.getProperty("bank.binding.path");
    String method = "GET";
    //String appcode = "eef21755de4a455aa747731069918f8d";
    // String appcode = PropertiesUtil.getProperty("bank.binding.appcode");
    String appcode = "c6f87afa60724ad19ec1a6e286dec216";
    Map<String, String> headers = new HashMap<String, String>();
    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    Map<String, String> querys = new HashMap<String, String>();
    querys.put("accountNo", bankNo);
    querys.put("idCard", idno);
    querys.put("mobile", phone);
    querys.put("name", realName);

    try {
      /**
       * 重要提示如下:
       * HttpUtils请从
       * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
       * 下载
       *
       * 相应的依赖请参照
       * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
       */
      HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
      System.out.println(response.toString());
      //获取response的body
      String resEntity = EntityUtils.toString(response.getEntity());
      System.out.println(resEntity);
      JSONObject respBody = JSON.parseObject(resEntity);
      String status = respBody.getString("status");
      msg = respBody.getString("msg");
      if (StringUtils.contains(status, "01")) {//认证通过为01
        User user = new User();
        user.setId(loginUser.getId());
        user.setPhone(phone);
        user.setBankNo(bankNo);
        user.setIdno(idno);
        user.setRealName(realName);
        user.setHeadpic(headpic);
        user.setStatus(3);
        userService.updateUser(user);
      } else {
        return ServerResponse.createByErrorMessage(msg);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      ServerResponse serverResponse = buSerevice.changeIntegral(loginUser.getId(), 2L);
      //查询当前用户的登陆信息
      User users = userService.getUserByUserId(loginUser.getId());
      RedisPoolUtil.set(session.getId(), JsonUtil.obj2String(users));
      return ServerResponse.createBySuccess(msg);
    } catch (Exception e) {
      e.printStackTrace();
      return ServerResponse.createByErrorMessage("操作失败");
    }
  }

  @ApiOperation("银行卡解绑")
  @RequestMapping(value = "relieveBinding.do", method = RequestMethod.POST)
  public ServerResponse relieveBinding(HttpServletRequest httpServletRequest) {
    User user = Const.checkUserLogin(httpServletRequest);
    if (user == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }
    return userService.relieveBinding(user.getId());
  }

  @PostMapping(value = "getPicAddress.do", headers = "content-type=multipart/form-data")
  @ApiOperation("个人中心-修改用户头像")
  public ServerResponse<String> updateUserHeadPic(HttpServletRequest httpServletRequest,
      @RequestParam(value = "file", required = true) MultipartFile multipartFile,
      HttpServletRequest request) {
   /* User loginUser = Const.checkUserLogin(httpServletRequest);
    if (loginUser == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }
    UploadPic pic = new UploadPic();
    String filePath = pic.upload(multipartFile);
    File file = new File(filePath);
    String fileName = file.getName();
    //文件请求路径
    String pealPath = PropertiesUtil.getProperty("file.server.peal") + fileName;
    User user = new User();
    user.setId(loginUser.getId());
    user.setHeadpic(pealPath);
    return userService.updateUser(user);*/
    String imgurl = "";
    try {
      String name = ossutil.uploadImg2Oss(multipartFile);
      imgurl = ossutil.getImgUrl(name);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ServerResponse.createBySuccess(imgurl);
  }

  @ApiOperation("查询当前用户个人信息")
  @RequestMapping(value = "getUserInfomation.do", method = RequestMethod.POST)
  public ServerResponse getUserInfomation(HttpServletRequest httpServletRequest) {
    User user = Const.checkUserLogin(httpServletRequest);
    if (user == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }
    return userService.getUserInfomation(user.getId());
  }


}
